#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h> 
#include <assert.h>
#include "public.h"
#include "file.h"

struct primitive_meas primitive_measurement;

static int file_open(const char * name);


int init_pm()
{
	int _pm = ~0;

	_pm = file_open(FILE_NAME);
	if (_pm < 0) {
		return -1;
	}

	ac_traces(MSG_LEVEL_INFO, "fd = %d!", _pm);
		
	primitive_measurement.pm = _pm;
	primitive_measurement.file_size = 0;
	primitive_measurement.data_size = 0;

	return 0;
}

static int file_open(const char * name)
{
	int file = ~0;

	assert(name != NULL);

	if (name == NULL) {
		ac_traces(MSG_LEVEL_ERROR, "file name is blank!");
		return -1;
	}

	file = open(FILE_NAME,  O_RDWR | O_CREAT | O_APPEND | O_NDELAY , S_IRUSR | S_IWUSR);
	if (file < 0){
		ac_traces(MSG_LEVEL_ERROR, "file open fail!");
		return -1;
	}

	return file;
}

int write_file(int fd, char * buf, size_t count)
{
	int byte = -1;

	ac_traces(MSG_LEVEL_VERBOSE, "fd = %d!", fd);

	assert(!(fd < 0));
	assert(buf != NULL);
	assert(count != 0);

	byte = write(fd, (void *)buf, count);

	return byte;
}

void close_file(int fd)
{
	assert(fd < 0);

	close(fd);
}


